package com.supertange.miniapp.wepet.common.interpretor;

import com.supertange.miniapp.wepet.common.service.RedisService;
import com.supertange.miniapp.wepet.common.vo.AjaxResult;
import com.supertange.miniapp.wepet.common.utils.JsonUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

@Log4j2
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    public RedisService redis;
    public static final String USER_REDIS_SESSION = "user-redis-session";

    /**
     * 拦截请求，在controller调用之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object arg2) throws Exception {
        String userId = request.getHeader("tokenId");
        String userToken = request.getHeader("token");

        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(userToken)) {
            String uniqueToken = (String) redis.get(USER_REDIS_SESSION + ":" + userId);
            if (StringUtils.isEmpty(uniqueToken) && StringUtils.isBlank(uniqueToken)) {
                log.info("请登陆...");
                returnErrorResponse(response, new AjaxResult().errorTokenMsg("登录已失效..."));
                return false;
            } else {
                if (!uniqueToken.equals(userToken)) {
                    log.warn("账号被挤出...");
                    returnErrorResponse(response, new AjaxResult().errorTokenMsg("账号被挤出..."));
                    return false;
                }
            }
        } else {
            log.info("请登录...");
            returnErrorResponse(response, new AjaxResult().errorTokenMsg("请重新登录..."));
            return false;
        }


        /**
         * 返回 false：请求被拦截，返回
         * 返回 true ：请求OK，可以继续执行，放行
         */
        return true;
    }

    public void returnErrorResponse(HttpServletResponse response, AjaxResult result)
            throws IOException, UnsupportedEncodingException {
        OutputStream out = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * 请求controller之后，渲染视图之前
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }

    /**
     * 请求controller之后，视图渲染之后
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

}
